package com.ffs.fsm.thread;


/**
 * 队列驱动
 * @author ffs80 created 2021/7/9
 */
public class QueueDriver {
    /**
     * 执行队列
     */
    private QueueExecutor executor;

    /**
     * 线程队列
     */
    private ITaskQueue<QueueDriverTask> queue;

    /**
     *
     */
    private String name;

    /**
     * 队列id
     */
    private long queueId;

    /**
     * 队列最大任务数
     */
    private int maxQueueSize;

    public QueueDriver(QueueExecutor executor, ITaskQueue<QueueDriverTask> queue, String name, long queueId, int maxQueueSize) {
        this.executor = executor;
        this.queue = queue;
        this.queueId = queueId;
        this.maxQueueSize = maxQueueSize;
        this.name = name;
    }

    /**
     * 任务添加
     * @return
     */
    public boolean addTask(QueueDriverTask task){
        if(task.getQueueId() != queueId){
            //任务执行队列错误
            return false;
        }
        synchronized (queue){
            if(queue.size() >= maxQueueSize){
                //抛弃该任务
                return false;
            }
            //添加任务
            boolean result = queue.offer(task);
            /**
             * TODO:该方法有问题，需要修改
             */
            task.setQueueTask(queue);
            if(result){
                if(!queue.isRunning()){
                    queue.setRunning(true);
                    executor.execute((Runnable) queue.poll());
                }
            }
            return result;
        }
    }

    public QueueExecutor getExecutor() {
        return executor;
    }

    public void setExecutor(QueueExecutor executor) {
        this.executor = executor;
    }

    public ITaskQueue<QueueDriverTask> getQueue() {
        return queue;
    }

    public void setQueue(ITaskQueue<QueueDriverTask> queue) {
        this.queue = queue;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public long getQueueId() {
        return queueId;
    }

    public void setQueueId(long queueId) {
        this.queueId = queueId;
    }

    public int getMaxQueueSize() {
        return maxQueueSize;
    }

    public void setMaxQueueSize(int maxQueueSize) {
        this.maxQueueSize = maxQueueSize;
    }
}
